/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.hva.bluepumpkin.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.ejb.CreateException;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import vn.hva.bluepumpkin.Constants;
import vn.hva.bluepumpkin.common.dto.UserProfileDTO;
import vn.hva.bluepumpkin.common.util.DataUtils;
import vn.hva.bluepumpkin.common.util.ServiceLocator;
import vn.hva.bluepumpkin.ejb.session.user.ManageUserRemote;
import vn.hva.bluepumpkin.ejb.session.user.ManageUserRemoteHome;
import vn.hva.bluepumpkin.util.RandomPassword;
import vn.hva.bluepumpkin.util.SendMail;

/**
 *
 * @author USER
 */
public class AjaxManageEmployee extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");

        int userid = Integer.parseInt(request.getParameter("userid"));

        try {
            ManageUserRemoteHome home = (ManageUserRemoteHome) ServiceLocator.getEjbRemoteHome("java:ManageUserSB",
                    ManageUserRemoteHome.class);
            ManageUserRemote remote = home.create();
            DateFormat df = new SimpleDateFormat(Constants.DATE_FORMAT);
            if (action.equals("addUser")) {
                HttpSession session = request.getSession();
                UserProfileDTO upDTO = (UserProfileDTO) session.getAttribute("user");
                String username = request.getParameter("username");
                String fullname = request.getParameter("fullname");
                String password = RandomPassword.getRandomString(8);
                String address = request.getParameter("address");
                String phone = request.getParameter("phone");
                String email = request.getParameter("email");
                String createby = upDTO.getUsername();
                boolean status = true;
                boolean gender = Boolean.parseBoolean(request.getParameter("gender"));
                Date bird = df.parse(request.getParameter("birthday"));
                Timestamp birthday = DataUtils.toTimestamp(bird);
                Integer role = new Integer(request.getParameter("role"));

                int uid = remote.insertEmployee(username, password, email, createby,
                        status, role, fullname, address, phone, gender, birthday, "image.gif");
                if (uid > 0) {
                    boolean isSend = SendMail.send(email, username, password, fullname);
                this.returnResult(out, true, String.valueOf(uid));
                } else {
                    this.returnResult(out, false, "0");
                }

            } else if (action.equals("updateProfile")) {
                String username = request.getParameter("username");
                String fullname = request.getParameter("fullname");
                String address = request.getParameter("address");
                String phone = request.getParameter("phone");
                String email = request.getParameter("email");
                boolean gender = Boolean.parseBoolean(request.getParameter("gender"));
                Date bird = df.parse(request.getParameter("birthday"));
                Timestamp birthday = DataUtils.toTimestamp(bird);
                int role = Integer.parseInt(request.getParameter("role"));
                if (remote.updateEmployeeByAdmin(userid, fullname, address, phone, email, gender, birthday, role)) {
                    this.returnResult(out, true, "");
                } else {
                    this.returnResult(out, false, "");
                }

            } else if (action.equals("deleteUser")) {
                if (remote.deleteEmployee(userid)) {
                    this.returnResult(out, true, String.valueOf(userid));
                } else {
                    this.returnResult(out, false, String.valueOf(userid) + " Userid");
                }
            } else if (action.equals("sendPasswordToEmployee")) {
                UserProfileDTO upDTO = remote.getEmployeeByID(new Integer(userid));
                System.out.println(upDTO.getEmail());
                System.out.println(upDTO.getPassword());
                System.out.println(upDTO.getFullname());

                boolean isSend = SendMail.send(upDTO.getEmail().trim(), upDTO.getUsername(), upDTO.getPassword(), upDTO.getFullname());
                //SendMail.send("smtp.gmail.com", "langvanhao@gmail.com", "password", "Lang van hao");
                if (isSend) {
                    this.returnResult(out, true, upDTO.getEmail());
                } else {
                    this.returnResult(out, false, upDTO.getEmail());
                }
            }

        } catch (CreateException ex) {
            this.returnResult(out, false, "");
            ex.printStackTrace();
        } catch (RemoteException ex) {
            this.returnResult(out, false, "");
            ex.printStackTrace();
        } catch (NamingException ex) {
            this.returnResult(out, false, "");
            ex.printStackTrace();
        } catch (Exception ex) {
            this.returnResult(out, false, "");
            ex.printStackTrace();
        }


    }

    public void returnResult(PrintWriter out, boolean rs, String note) {
        out.println("<?xml version=\"1.0\"?> ");
        out.println("<root>");
        out.println("<result>" + rs + "</result>");
        out.println("<note><![CDATA[" + note + "]]></note>");
        out.println("</root>");
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
